package com.good.child.widgets;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

/**
 * Create by xiaojie on 2024/8/25
 */
public class WaveView extends View {
    private Paint paint;
    private Path path;
    private ValueAnimator animator;

    private float waveAmplitude = 50; // 波幅
    private float waveFrequency = 0.05f; // 波频率
    private float waveOffset = 0; // 波偏移

    public WaveView(Context context) {
        super(context);
        init();
    }

    public WaveView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public WaveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(0xFF00FF00); // 设置颜色为绿色
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);

        path = new Path();

        animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(2000); // 动画持续时间
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                waveOffset += 5; // 控制波动的速度
                invalidate(); // 重新绘制
            }
        });
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        path.reset();
        path.moveTo(0, getHeight() / 2);

        // 绘制波浪线
        for (float x = 0; x < getWidth(); x++) {
            float y = (float) (waveAmplitude * Math.sin(waveFrequency * x + waveOffset) + getHeight() / 2);
            path.lineTo(x, y);
        }

        canvas.drawPath(path, paint);
    }
}
